#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/8/13 15:56
# @USER    : Shengji He
# @File    : Combinations.py
# @Software: PyCharm
# @Version  : Python-
# @TASK:
from typing import List


class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        """
        Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

        Example:
            Input: n = 4, k = 2
            Output:
                [
                  [2,4],
                  [3,4],
                  [2,3],
                  [1,2],
                  [1,3],
                  [1,4],
                ]

        :param n:
        :param k:
        :return:
        """
        ans = []
        c = self.uniqueCombinations([i for i in range(1, n + 1)], k)
        while True:
            try:
                ans.append(next(c))
            except StopIteration:
                break
        return ans

    def uniqueCombinations(self, items, n):
        def afterIthItem(items, i):
            return items[i + 1:]
        return self._combinators(afterIthItem, items, n)

    def _combinators(self, _handle, items, n):
        if n == 0:
            yield []
        for i, item in enumerate(items):
            this_one = [item]
            for cc in self._combinators(_handle, _handle(items, i), n - 1):
                yield this_one + cc


if __name__ == '__main__':
    n = 4
    k = 2
    S = Solution()
    print(S.combine(n, k))
    print('done')
